package com.coder.algorithm.leetcode

/**
 * [14. 最长公共前缀](https://leetcode-cn.com/problems/longest-common-prefix/)
 *
 * @author yuhus
 * @date: 2022/3/15
 */
class l_0014 {
    fun longestCommonPrefix(strs: Array<String>): String {
        if (strs.isEmpty()) {
            return ""
        }
        var len = strs[0].length
        var res = strs[0].toCharArray()
        for (i in 1 until strs.size) {
            val str = strs[i]
            if (len > str.length) {
                len = str.length
            }
            for (j in 0 until len) {
                if (res[j] != str[j]) {
                    len = j
                    break
                }
            }
            if (len == 0) {
                break
            }
        }
        return String(res).substring(0, len)
    }
}